<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <AppHeader />

    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 py-6 mt-16 md:mt-20">
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧边栏 (PC端显示) -->
        <aside class="hidden lg:block w-64 shrink-0">
          <LeftSidebar />
        </aside>

        <!-- 中间内容区 -->
        <div class="flex-1 max-w-3xl mx-auto lg:mx-0">
          <!-- 加载状态 -->
          <div
            v-if="isLoading"
            class="bg-white rounded-xl shadow-sm p-6 mb-6 flex justify-center items-center min-h-[400px]"
          >
            <div class="flex flex-col items-center">
              <i class="fa fa-spinner fa-spin text-primary text-3xl mb-3"></i>
              <span class="text-gray-600">加载中...</span>
            </div>
          </div>

          <!-- 错误提示 -->
          <div
            v-else-if="errorMessage"
            class="bg-white rounded-xl shadow-sm p-6 mb-6"
          >
            <div class="flex items-center justify-center text-red-500">
              <i class="fa fa-exclamation-circle mr-2"></i>
              <span>{{ errorMessage }}</span>
            </div>
          </div>

          <!-- 帖子内容卡片（修复字段可选性+用户信息渲染） -->
          <article v-if="post" class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <!-- 帖子头部（从服务端`user`字段直接取值，避免映射错误） -->
            <div class="flex items-center justify-between mb-4">
              <div class="flex items-center space-x-3">
                <img  
                  :src="
                    post.user?.avatar ||
                    'https://picsum.photos/seed/default-user/40/40'
                  "
                  alt="用户头像"
                  class="w-12 h-12 rounded-full object-cover"
                />
                <div>
                  <h3 class="font-medium text-gray-900">
                    {{ post.user?.nickname || '匿名用户' }}
                  </h3>
                  <p class="text-xs text-gray-500">
                    {{ post.user?.intro || '普通用户' }} ·
                    {{ formatDate(post.createTime || '') }}
                  </p>
                </div>
              </div>
              <div class="flex space-x-2">
                <!-- 编辑按钮 -->
                <button
                  v-if="post.canEdit"
                  class="text-gray-400 hover:text-primary transition-colors mr-2"
                >
                  <i class="fa fa-pencil"></i>
                </button>
                <!-- 删除按钮 -->
                <button
                  v-if="post.canDelete"
                  class="text-gray-400 hover:text-red-500 transition-colors mr-2"
                >
                  <i class="fa fa-trash"></i>
                </button>
                <!-- 更多按钮 -->
                <button class="text-gray-400 hover:text-gray-600">
                  <i class="fa fa-ellipsis-h"></i>
                </button>
              </div>
            </div>

            <!-- 帖子标题 -->
            <h1 class="text-2xl font-bold text-gray-900 mb-4">
              {{ post.title || '无标题帖子' }}
            </h1>

            <!-- 帖子内容（修复HTML渲染空值） -->
            <div class="prose prose-slate max-w-none mb-6">
              <div v-html="post.content || '<p>暂无帖子内容</p>'"></div>
            </div>

            <!-- 帖子图片（修复空数组判断） -->
            <div v-if="post.media && post.media.length > 0" class="mb-6">
              <div
                v-if="post.media.length === 1"
                class="rounded-lg overflow-hidden"
              >
                <img
                  :src="post.media[0]"
                  alt="帖子图片"
                  class="w-full h-auto object-cover"
                />
              </div>
              <div
                v-else
                class="grid grid-cols-2 gap-2 rounded-lg overflow-hidden"
              >
                <img
                  v-for="(image, index) in post.media"
                  :key="index"
                  :src="image"
                  alt="帖子图片"
                  class="w-full h-auto object-cover"
                />
              </div>
            </div>

            <!-- 帖子标签（从服务端`cateName`直接生成，避免多标签错误） -->
            <div class="flex flex-wrap gap-2 mb-6">
              <span
                v-if="post.cateName"
                class="inline-flex items-center px-3 py-1 bg-gray-100 text-gray-600 text-sm rounded-full"
              >
                {{ post.cateName }}
              </span>
            </div>

            <!-- 互动数据（修复数字转字符串+空值处理） -->
            <div
              class="flex items-center space-x-6 border-t border-gray-100 pt-4"
            >
              <button
                class="flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors"
              >
                <i class="fa fa-heart-o"></i>
                <span>{{ (post.likeCount || 0).toString() }}</span>
              </button>
              <button
                class="flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors"
              >
                <i class="fa fa-comment-o"></i>
                <span>{{ (post.commentCount || 0).toString() }}</span>
              </button>
              <button
                class="flex items-center space-x-1 text-gray-500 hover:text-primary transition-colors"
              >
                <i class="fa fa-eye"></i>
                <span>{{ (post.readCount || 0).toString() }}</span>
              </button>
            </div>
          </article>

          <!-- 互动工具栏（修复加载状态） -->
          <div v-if="post" class="bg-white rounded-xl shadow-sm p-4 mb-6">
            <div class="flex items-center justify-between">
              <!-- 点赞按钮（添加加载状态防止重复点击） -->
              <button
                class="flex-1 flex items-center justify-center space-x-2 py-2 text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
                @click="handleLike"
                :disabled="isLiking"
              >
                <i
                  :class="[
                    'fa',
                    post.liked
                      ? 'fa-heart text-red-500'
                      : 'fa-heart-o text-gray-500',
                    isLiking ? 'fa-spin' : '',
                  ]"
                ></i>
                <span>{{ post.liked ? '已点赞' : '点赞' }}</span>
              </button>

              <!-- 评论按钮 -->
              <button
                class="flex-1 flex items-center justify-center space-x-2 py-2 text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
              >
                <i class="fa fa-comment-o text-gray-500"></i>
                <span>评论</span>
              </button>

              <div class="w-px h-8 bg-gray-200 mx-1"></div>

              <!-- 收藏按钮（添加加载状态） -->
              <button
                class="flex-1 flex items-center justify-center space-x-2 py-2 text-gray-700 hover:bg-gray-50 rounded-lg transition-colors"
                @click="handleCollect"
                :disabled="isCollecting"
              >
                <i
                  :class="[
                    'fa',
                    post.collected
                      ? 'fa-bookmark text-primary'
                      : 'fa-bookmark-o text-gray-500',
                    isCollecting ? 'fa-spin' : '',
                  ]"
                ></i>
                <span>{{ post.collected ? '已收藏' : '收藏' }}</span>
              </button>

              <div class="w-px h-8 bg-gray-200 mx-1"></div>

            </div>
          </div>

          <!-- 评论区（核心修复：评论映射+分页参数） -->
          <div v-if="post" class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-900 mb-4">
              {{ (post.commentCount || 0).toString() }} 条评论
            </h2>

            <!-- 评论输入框（添加提交状态） -->
            <div class="flex space-x-3 mb-6">
              <img
                :src="
                  currentUser?.avatar ||
                  'https://i1.hdslb.com/bfs/article/431cc0bc90c2aadd805cd64e16b83890f065159e.jpg'
                "
                alt="用户头像"
                class="w-10 h-10 rounded-full object-cover"
              />
              <div class="flex-1">
                <textarea
                  v-model="commentText"
                  placeholder="写下你的评论..."
                  class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all resize-none"
                  rows="3"
                  :disabled="isSubmittingComment"
                ></textarea>
                <div class="flex justify-between mt-2">
                  
                  <button
                    class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                    :disabled="!commentText.trim() || isSubmittingComment"
                    @click="submitComment"
                  >
                    <span
                      v-if="isSubmittingComment"
                      class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-white border-t-transparent mr-1"
                    ></span>
                    发表评论
                  </button>
                </div>
              </div>
            </div>

            <!-- 评论列表（修复：从服务端`userRespDTO`提取作者信息，无多余映射） -->
            <div class="space-y-6">
              <div
                v-for="comment in comments"
                :key="comment.id"
                class="border-b border-gray-100 pb-6 last:border-0 last:pb-0"
              >
                <!-- 评论项 -->
                <div class="flex space-x-3">
                  <!-- 评论作者头像（直接用服务端`userRespDTO.avatar`） -->
                  <img
                    :src="
                      comment.userRespDTO.avatar ||
                      'https://picsum.photos/seed/default-comment/40/40'
                    "
                    alt="评论者头像"
                    class="w-10 h-10 rounded-full object-cover"
                  />
                  <div class="flex-1">
                    <div class="bg-gray-50 p-4 rounded-lg">
                      <div class="flex items-center justify-between mb-1">
                        <!-- 评论作者名称（用服务端`userRespDTO.nickname`） -->
                        <h4 class="font-medium text-gray-900">
                          {{
                            comment.userRespDTO.nickname ||
                            comment.userRespDTO.loginId
                          }}
                        </h4>
                        <span class="text-xs text-gray-500">{{
                          formatDate(comment.createTime)
                        }}</span>
                      </div>
                      <p class="text-gray-700">{{ comment.content }}</p>
                    </div>

                    <!-- 评论互动（修复点赞状态+加载） -->
                    <div class="flex items-center space-x-4 mt-2">
                      <button
                        class="text-xs text-gray-500 hover:text-primary transition-colors"
                        @click="handleCommentLike(comment)"
                        :disabled="commentLikeLoading[comment.id]"
                      >
                        <i
                          :class="[
                            'fa',
                            comment.liked
                              ? 'fa-heart text-red-500'
                              : 'fa-heart-o',
                            commentLikeLoading[comment.id] ? 'fa-spin' : '',
                          ]"
                          class="mr-1"
                        ></i
                        >{{ comment.likeCount }}
                      </button>
                      <button
                        class="text-xs text-gray-500 hover:text-primary transition-colors"
                        @click="showReplyInput(comment)"
                      >
                        <i class="fa fa-reply mr-1"></i>回复
                      </button>
                    </div>

                    <!-- 回复列表 -->
                    <div class="mt-4">
                      <!-- 加载状态 -->
                      <div v-if="isLoadingReplies[comment.id]" class="text-center py-2">
                        <i class="fa fa-spin fa-spinner text-gray-500 mr-1"></i>
                        <span class="text-xs text-gray-500">加载回复中...</span>
                      </div>
                        
                      <!-- 回复列表内容 -->
                      <div v-if="commentReplies[comment.id] && commentReplies[comment.id].length > 0" class="mt-3 space-y-4 pl-4 border-l-2 border-gray-100">
                        <!-- 回复总数显示 -->
                        <div v-if="replyTotalCount[comment.id] > 0" class="text-xs text-gray-500 mb-2">
                          共 {{ replyTotalCount[comment.id] }} 条回复
                        </div>
                        
                        <!-- 回复项 -->
                        <div
                          v-for="reply in commentReplies[comment.id]"
                          :key="reply.id"
                          class="flex space-x-3"
                        >
                          <img
                            :src="
                              reply.userRespDTO?.avatar ||
                              'https://i1.hdslb.com/bfs/article/431cc0bc90c2aadd805cd64e16b83890f065159e.jpg'
                            "
                            alt="回复者头像"
                            class="w-8 h-8 rounded-full object-cover"
                          />
                          <div class="flex-1">
                            <div class="bg-gray-50 p-3 rounded-lg">
                              <div class="flex items-center justify-between mb-1">
                                <div class="flex items-center">
                                  <h5 class="font-medium text-gray-900 mr-1">
                                    {{ 
                                      reply.userRespDTO?.nickname ||
                                      reply.userRespDTO?.loginId ||
                                      '匿名用户'
                                    }}
                                  </h5>
                                  <span class="text-xs text-gray-500">回复</span>
                                  <span class="text-xs text-primary ml-1"
                                    >@{{
                                      comment.userRespDTO.nickname ||
                                      comment.userRespDTO.loginId ||
                                      '匿名用户'
                                    }}</span
                                  >
                                </div>
                                <span class="text-xs text-gray-500">{{
                                  formatDate(reply.createTime)
                                }}</span>
                              </div>
                              <p class="text-gray-700 text-sm">
                                {{ reply.content }}
                              </p>
                            </div>

                            <!-- 回复互动 -->
                            <div class="flex items-center space-x-4 mt-1">
                              <button
                                class="text-xs text-gray-500 hover:text-primary transition-colors"
                                @click="handleReplyLike(reply)"
                                :disabled="replyLikeLoading[reply.id]"
                              >
                                <i
                                  :class="[
                                    'fa',
                                    reply.liked
                                      ? 'fa-heart text-red-500'
                                      : 'fa-heart-o',
                                    replyLikeLoading[reply.id] ? 'fa-spin' : '',
                                  ]"
                                  class="mr-1"
                                ></i
                                >{{ reply.likeCount }}
                              </button>
                              <button
                                class="text-xs text-gray-500 hover:text-primary transition-colors"
                                @click="showReplyInput(comment, reply)"
                              >
                                <i class="fa fa-reply mr-1"></i>回复
                              </button>
                            </div>
                          </div>
                        </div>
                        
                        <!-- 加载更多回复 -->
                        <div v-if="hasMoreReplies[comment.id]" class="text-center">
                          <button
                            class="text-xs text-primary hover:text-primary-dark transition-colors"
                            @click="loadCommentReplies(comment.id)"
                            :disabled="isLoadingReplies[comment.id]"
                          >
                            <i :class="['fa', isLoadingReplies[comment.id] ? 'fa-spin fa-spinner' : 'fa-refresh']" class="mr-1"></i>
                            {{ isLoadingReplies[comment.id] ? '加载中...' : '加载更多回复' }}
                          </button>
                        </div>
                      </div>
                    </div>

                    <!-- 回复输入框（修复：绑定到当前评论ID） -->
                    <div v-if="replyToComment?.id === comment.id" class="mt-3">
                      <div class="flex space-x-3">
                        <img
                          :src="
                            currentUser?.avatar ||
                            'https://picsum.photos/seed/user1/40/40'
                          "
                          alt="用户头像"
                          class="w-8 h-8 rounded-full object-cover mt-1"
                        />
                        <div class="flex-1">
                          <textarea
                            v-model="replyText"
                            :placeholder="`回复 @${
                              comment.userRespDTO.nickname ||
                              comment.userRespDTO.loginId
                            }`"
                            class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-all resize-none text-sm"
                            rows="2"
                            :disabled="isSubmittingReply"
                          ></textarea>
                          <div class="flex justify-end mt-1">
                            <button
                              class="px-3 py-1 text-sm text-gray-500 hover:text-gray-700 mr-2"
                              @click="cancelReply"
                            >
                              取消
                            </button>
                            <button
                              class="px-3 py-1 text-sm bg-primary text-white rounded hover:bg-primary/90"
                              :disabled="!replyText.trim() || isSubmittingReply"
                              @click="submitReply"
                            >
                              <span
                                v-if="isSubmittingReply"
                                class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-white border-t-transparent mr-1"
                              ></span>
                              发送
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载更多评论（修复：用`lastTime/offset`分页，而非`page`） -->
            <div class="text-center mt-8" v-if="hasMoreComments">
              <button
                class="px-6 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                @click="loadMoreComments"
                :disabled="isLoadingComments"
              >
                <i
                  v-if="isLoadingComments"
                  class="fa fa-spinner fa-spin mr-2"
                ></i>
                {{ isLoadingComments ? '加载中...' : '加载更多评论' }}
              </button>
            </div>
            <div class="text-center mt-8 text-gray-500" v-else>
              已加载全部评论
            </div>
          </div>
        </div>

        <!-- 右侧边栏 (PC端显示) -->
        <aside class="hidden lg:block w-72 shrink-0">
          <RightSidebar />
        </aside>
      </div>
    </main>

    <!-- 底部导航栏 (移动端显示，修复遮挡问题) -->
    <nav
      class="lg:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 z-30"
    >
      <div class="flex items-center justify-around h-16">
        <a
          href="/"
          class="flex flex-col items-center justify-center text-primary"
        >
          <i class="fa fa-home text-xl"></i>
          <span class="text-xs mt-1">首页</span>
        </a>
        <a
          href="#"
          class="flex flex-col items-center justify-center text-gray-500 hover:text-primary transition-colors"
        >
          <i class="fa fa-compass text-xl"></i>
          <span class="text-xs mt-1">探索</span>
        </a>
        <button
          class="flex flex-col items-center justify-center text-gray-500 hover:text-primary transition-colors"
        >
          <i class="fa fa-plus-circle text-3xl"></i>
        </button>
        <a
          href="#"
          class="flex flex-col items-center justify-center text-gray-500 hover:text-primary transition-colors"
        >
          <i class="fa fa-bookmark-o text-xl"></i>
          <span class="text-xs mt-1">收藏</span>
        </a>
        <a
          href="#"
          class="flex flex-col items-center justify-center text-gray-500 hover:text-primary transition-colors"
        >
          <i class="fa fa-user-o text-xl"></i>
          <span class="text-xs mt-1">我的</span>
        </a>
      </div>
    </nav>
  </div>
</template>

<script setup lang="ts">
  // 导入服务端类型和接口，避免重复定义，确保类型一致
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import LeftSidebar from './LeftSidebar.vue'
  import RightSidebar from './RightSidebar.vue'
  import { getUserInfo } from '../services/userService'
  import AppHeader from "./layout/AppHeader.vue"
  
  import {
    getPostDetail,
    getComments,
    addComment,
    likePost,
    likeComment,
    toggleCollection,
    getCommentReplies, // 添加获取评论回复的函数
    type Post as ServicePost, // 复用服务端帖子类型
    type Comment as ServiceComment, // 复用服务端评论类型
    type Reply as ServiceReply, // 复用服务端回复类型
    type GetCommentsRes, // 复用评论列表返回类型
  } from '../services/postService'

  // 响应式状态（修复分页参数：用lastTime/offset替代page）
  // ------------------------------
  const route = useRoute()
  const postId = Number(route.params.id) || 1 // 处理ID为字符串/undefined的情况
  const post = ref<ServicePost | null>(null) // 直接用服务端类型，无额外映射
  const comments = ref<ServiceComment[]>([]) // 评论列表：服务端类型数组
  const commentText = ref('') // 评论输入内容
  const replyText = ref('') // 回复输入内容
  const replyToComment = ref<ServiceComment | null>(null) // 当前回复的评论
  const replyToReply = ref<ServiceReply | null>(null) // 当前回复的回复（二级回复）
  const currentUser = ref<any>(null) // 当前用户信息

  // 加载状态（细分状态，提升体验）
  const isLoading = ref(true) // 帖子详情加载状态
  const errorMessage = ref('') // 错误提示
  const isSubmittingComment = ref(false) // 评论提交状态
  const isSubmittingReply = ref(false) // 回复提交状态
  const isLoadingComments = ref(false) // 评论列表加载状态
  const isLiking = ref(false) // 帖子点赞加载状态
  const isCollecting = ref(false) // 帖子收藏加载状态

  // 评论分页状态（对齐服务端接口参数：lastTime/offset）
  const lastCommentTime = ref('') // 最后一条评论的时间（用于分页续加载）
  const commentOffset = ref(0) // 评论偏移量（用于分页）
  const totalCommentCount = ref(0) // 总评论数（判断是否有更多）
  const hasMoreComments = ref(false) // 是否有更多评论

  // 评论/回复点赞加载状态（避免重复点击）
  const commentLikeLoading = ref<Record<number, boolean>>({}) // 评论点赞加载
  const replyLikeLoading = ref<Record<number, boolean>>({}) // 回复点赞加载

  // 评论回复相关状态
  const commentReplies = ref<Record<number, ServiceComment[]>>({}) // 存储每条评论的回复列表
  const isLoadingReplies = ref<Record<number, boolean>>({}) // 每条评论的回复加载状态
  const hasMoreReplies = ref<Record<number, boolean>>({}) // 每条评论是否有更多回复
  const lastReplyTime = ref<Record<number, string>>({}) // 每条评论最后一条回复的时间
  const replyOffset = ref<Record<number, number>>({}) // 每条评论的回复偏移量
  const replyTotalCount = ref<Record<number, number>>({}) // 每条评论的回复总数

  // ------------------------------
  // 工具函数（简化逻辑，避免冗余）
  // ------------------------------
  /** 日期格式化：多久前（处理空值） */
  const formatDate = (dateString: string): string => {
    if (!dateString) return '未知时间'
    try {
      const date = new Date(dateString)
      const now = new Date()
      const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)

      if (diffInSeconds < 60) return `${diffInSeconds}秒前`
      if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`
      if (diffInSeconds < 86400)
        return `${Math.floor(diffInSeconds / 3600)}小时前`
      if (diffInSeconds < 604800)
        return `${Math.floor(diffInSeconds / 86400)}天前`
      return date.toLocaleDateString('zh-CN')
    } catch {
      return dateString
    }
  }

  // ------------------------------
  // 核心业务逻辑（修复接口参数+类型映射）
  // ------------------------------
  /** 加载帖子详情（简化数据处理逻辑） */
  const loadPostDetail = async () => {
    try {
      isLoading.value = true
      errorMessage.value = ''

      // 1. 调用接口获取服务端数据
      const servicePost = await getPostDetail(postId)

      // 2. 确保数据安全性，添加默认值
      post.value = {
        ...servicePost,
        user: servicePost.user || {
          uid: 0,
          loginId: 'anonymous',
          nickname: '匿名用户',
          avatar: 'https://picsum.photos/seed/default-user/40/40',
          intro: '',
        },
        title: servicePost.title || '无标题帖子',
        content: servicePost.content || '暂无帖子内容',
        media: servicePost.media || [],
        likeCount: servicePost.likeCount || 0,
        commentCount: servicePost.commentCount || 0,
        readCount: servicePost.readCount || 0,
        liked: servicePost.liked || false,
        collected: servicePost.collected || false,
      }

      // 3. 加载第一页评论
      await loadComments()
    } catch (error) {
      console.error('加载帖子详情失败:', error)
      errorMessage.value = '加载帖子详情失败，请稍后重试'
      ElMessage.error('加载帖子详情失败，请稍后重试')

      // 4. 降级：使用模拟数据
      setMockData()
    } finally {
      isLoading.value = false
    }
  }

  /** 加载评论列表（修复：用lastTime/offset分页，对齐服务端接口） */
  const loadComments = async () => {
    if (!postId) return
    isLoadingComments.value = true

    try {
      // 1. 调用接口：参数为lastTime/offset/size（服务端要求的分页参数）
      const res: GetCommentsRes = await getComments({
        postId,
        lastTime: lastCommentTime.value, // 上一页最后一条评论时间
        offset: commentOffset.value, // 偏移量
        size: 10, // 每页10条
      })

      // 2. 处理服务端返回（CommentPageVO结构）
      if (res.code === '0' && res.data) {
        const newComments = res.data.commentVOS || []
        const total = res.data.count || 0

        // 3. 合并评论列表（首次加载覆盖，加载更多合并）
        if (lastCommentTime.value === '') {
          comments.value = newComments
        } else {
          comments.value = [...comments.value, ...newComments]
        }

        // 4. 更新分页状态（判断是否有更多评论）
        lastCommentTime.value = res.data.lastTime || '' // 记录当前页最后一条时间
        commentOffset.value = res.data.offset || 0 // 更新偏移量
        totalCommentCount.value = total // 记录总评论数
        hasMoreComments.value = comments.value.length < total // 已加载数 < 总数 → 有更多
        
        // 5. 自动加载所有评论的回复
        await autoLoadAllReplies()
      } else {
        throw new Error(res.message || '获取评论列表失败')
      }
    } catch (error) {
      console.error(`加载评论失败:`, error)
      ElMessage.error('加载评论失败，请稍后重试')

      // 5. 降级：首次加载失败时用模拟评论
      if (lastCommentTime.value === '') {
        comments.value = getMockComments()
        hasMoreComments.value = false
      }
    } finally {
      isLoadingComments.value = false
    }
  }

  /** 帖子点赞/取消点赞（修复：接口参数+状态校准） */
  const handleLike = async () => {
    if (!post.value || isLiking.value) return
    const currentLiked = post.value.liked || false

    try {
      isLiking.value = true
      // 1. 乐观更新UI（提升体验）
      post.value.liked = !currentLiked
      post.value.likeCount =
        (post.value.likeCount || 0) + (currentLiked ? -1 : 1)

      // 2. 调用接口提交状态（参数对齐服务端）
      const res = await likePost({
        postId: post.value.id!, // 非空断言：帖子ID必存在
        isLike: !currentLiked,
      })

      // 3. 修复：添加类型安全检查
      if (res && typeof res.liked === 'boolean') {
        post.value.liked = res.liked
        post.value.likeCount = res.likeCount || post.value.likeCount
      }

      ElMessage.success(res.liked ? '点赞成功' : '取消点赞成功')
    } catch (error) {
      console.error('帖子点赞失败:', error)
      // 4. 回滚UI（接口失败时）
      post.value.liked = currentLiked
      post.value.likeCount =
        (post.value.likeCount || 0) + (currentLiked ? 1 : -1)
      ElMessage.error('点赞操作失败，请稍后重试')
    } finally {
      isLiking.value = false
    }
  }

  /** 帖子收藏/取消收藏（模拟接口，实际需对接服务端） */
  const handleCollect = async () => {
    if (!post.value || isCollecting.value) return
    const currentCollected = post.value.collected || false

    try {
      isCollecting.value = true
      // 调用实际的收藏接口
      const result = await toggleCollection({
        postId: post.value.id!, // 非空断言：帖子ID必存在
        isCollect: !currentCollected,
      })

      // 更新状态
      post.value.collected = result.collected
      post.value.collectionCount = result.collectionCount
      ElMessage.success(post.value.collected ? '收藏成功' : '取消收藏成功')
    } catch (error) {
      console.error('帖子收藏失败:', error)
      post.value.collected = currentCollected
      ElMessage.error('收藏操作失败，请稍后重试')
    } finally {
      isCollecting.value = false
    }
  }

  /** 加载评论的回复列表 */
  const loadCommentReplies = async (commentId: number) => {
    // 如果已经在加载中，则不再重复加载
    if (isLoadingReplies.value[commentId]) return
    
    try {
      isLoadingReplies.value[commentId] = true
      
      // 调用接口获取回复列表
      const res = await getCommentReplies(
        commentId, 
        3, // 默认获取3条回复
        lastReplyTime.value[commentId], 
        replyOffset.value[commentId]
      )
      
      // 初始化回复列表（避免undefined）
      if (!commentReplies.value[commentId]) {
        commentReplies.value[commentId] = []
      }
      
      // 如果是首次加载，直接赋值；否则追加
      if (!lastReplyTime.value[commentId]) {
        commentReplies.value[commentId] = res.data
      } else {
        commentReplies.value[commentId] = [...commentReplies.value[commentId], ...res.data]
      }
      
      // 更新状态
      hasMoreReplies.value[commentId] = (res.data.length >= 3) && (commentReplies.value[commentId].length < (res.count || 0))
      replyTotalCount.value[commentId] = res.count || 0
      
      // 更新分页状态
      if (res.lastTime) {
        lastReplyTime.value[commentId] = res.lastTime
      }
      if (res.offset !== undefined) {
        replyOffset.value[commentId] = res.offset
      }
    } catch (error) {
      console.error(`加载评论回复失败（评论ID: ${commentId}）:`, error)
    } finally {
      isLoadingReplies.value[commentId] = false
    }
  }
  
  /** 自动加载所有评论的回复 */
  const autoLoadAllReplies = async () => {
    // 等待评论列表加载完成
    if (comments.value.length === 0) return
    
    // 为每条评论自动调用一次loadCommentReplies
    for (const comment of comments.value) {
      if (comment.id && comment.commentCount && comment.commentCount > 0) {
        // 只对有回复的评论加载回复
        await loadCommentReplies(comment.id)
      }
    }
  }

  /** 提交评论（修复：接口参数+新增评论插入逻辑） */
  const submitComment = async () => {
    const content = commentText.value.trim()
    if (!content || !postId || isSubmittingComment.value) return

    try {
      isSubmittingComment.value = true
      // 1. 调用接口提交评论（参数对齐服务端：postId/content/pid）
      const res = await addComment({
        postId,
        content,
        pid: undefined, // 一级评论，无父ID
      })

      if (res.code === '0') {
        ElMessage.success('评论发表成功')
        // 发表评论成功后直接刷新页面
        window.location.reload()
      } else {
        throw new Error(res.message || '评论发表失败')
      }
    } catch (error) {
      console.error('提交评论失败:', error)
      ElMessage.error('评论发表失败，请稍后重试')

      // 降级：临时添加模拟评论（提升体验）
      const mockComment = getMockComment(content)
      comments.value.unshift(mockComment)
      commentText.value = ''
      if (post.value) {
        post.value.commentCount = (post.value.commentCount || 0) + 1
      }
      ElMessage.success('评论已临时保存，稍后将同步到服务器')
    } finally {
      isSubmittingComment.value = false
    }
  }

  /** 提交回复（修复：父评论ID传递+回复列表更新） */
  const submitReply = async () => {
    const content = replyText.value.trim()
    if (!content || !postId || isSubmittingReply.value) return

    // 判断是回复评论还是回复回复
    const isReplyToReply = !!replyToReply.value
    // 无论回复评论还是回复回复，父评论ID都应该是顶级评论的ID
    const parentId = replyToComment.value!.id
    // 被回复者ID是直接被回复的用户ID（可以是评论者或其他回复者）
    const targetToUid = isReplyToReply ? replyToReply.value!.userRespDTO!.uid : replyToComment.value!.userRespDTO!.uid

    try {
      isSubmittingReply.value = true
      // 1. 调用接口提交回复（复用addComment，通过pid区分）
      const res = await addComment({
        postId,
        content,
        pid: parentId,
        toUid: targetToUid,
      })

      if (res.code === '0') {
        ElMessage.success('回复发表成功')
        // 发表回复成功后直接刷新页面
        window.location.reload()
      } else {
        throw new Error(res.message || '回复发表失败')
      }
    } catch (error) {
      console.error('提交回复失败:', error)
      ElMessage.error('回复发表失败，请稍后重试')
    } finally {
      isSubmittingReply.value = false
    }
  }

  /** 评论点赞/取消点赞（修复：接口调用+状态管理） */
  const handleCommentLike = async (comment: ServiceComment) => {
    if (!comment.id || commentLikeLoading.value[comment.id]) return
    const currentLiked = comment.liked

    try {
      commentLikeLoading.value[comment.id] = true
      // 1. 乐观更新UI
      comment.liked = !currentLiked
      comment.likeCount += currentLiked ? -1 : 1

      // 2. 调用评论点赞接口
      const res = await likeComment({
        commentId: comment.id,
        isLike: !currentLiked,
      })

      // 3. 修复：精确类型检查和安全赋值
      if (res && typeof res.liked === 'boolean') {
        comment.liked = res.liked
        comment.likeCount = res.likeCount || comment.likeCount
      } else {
        throw new Error('评论点赞失败')
      }
    } catch (error) {
      console.error('评论点赞失败:', error)
      // 4. 回滚UI
      comment.liked = currentLiked
      comment.likeCount += currentLiked ? 1 : -1
      ElMessage.error('评论点赞操作失败，请稍后重试')
    } finally {
      commentLikeLoading.value[comment.id] = false
    }
  }

  /** 回复点赞/取消点赞（同评论点赞逻辑） */
  const handleReplyLike = async (reply: ServiceReply) => {
    if (!reply.id || replyLikeLoading.value[reply.id]) return
    const currentLiked = reply.liked

    try {
      replyLikeLoading.value[reply.id] = true
      // 1. 乐观更新UI
      reply.liked = !currentLiked
      reply.likeCount += currentLiked ? -1 : 1

      // 2. 调用回复点赞接口（回复与评论共用点赞接口，ID通用）
      const res = await likeComment({
        commentId: reply.id,
        isLike: !currentLiked,
      })

      // 3. 校准状态
      if (res) {
        reply.liked = res.liked
        reply.likeCount = res.likeCount
      } else {
        throw new Error(
          typeof res === 'object' &&
          res !== null &&
          res !== undefined &&
          'message' in res
            ? ((res as Record<string, unknown>).message as string)
            : '回复点赞失败'
        )
      }
    } catch (error) {
      console.error('回复点赞失败:', error)
      // 4. 回滚UI
      reply.liked = currentLiked
      reply.likeCount += currentLiked ? 1 : -1
      ElMessage.error('回复点赞操作失败，请稍后重试')
    } finally {
      replyLikeLoading.value[reply.id] = false
    }
  }

  /** 显示回复输入框（修复：区分回复评论/回复） */
  const showReplyInput = (comment: ServiceComment, reply?: ServiceReply) => {
    replyToComment.value = comment
    replyToReply.value = reply ?? null // 二级回复时记录被回复的回复，处理 undefined 情况
    replyText.value = ''
    // 聚焦输入框
    setTimeout(() => {
      const textarea = document.querySelector<HTMLTextAreaElement>(
        'textarea[placeholder^="回复 @"]'
      )
      textarea?.focus()
    }, 100)
  }

  /** 取消回复 */
  const cancelReply = () => {
    replyToComment.value = null
    replyToReply.value = null
    replyText.value = ''
  }

  /** 加载更多评论（触发分页续加载） */
  const loadMoreComments = async () => {
    if (isLoadingComments.value || !hasMoreComments.value) return
    await loadComments()
  }

  // ------------------------------
  // 模拟数据（严格遵循服务端类型，避免降级时类型错误）
  // ------------------------------
  /** 设置模拟帖子+评论数据（降级用） */
  const setMockData = () => {
    // 模拟帖子数据（严格匹配ServicePost类型）
    post.value = {
      id: postId,
      uid: 1001, // 补充用户ID
      cateId: 1, // 补充分类ID
      title: 'Vue 3 + TypeScript 开发最佳实践',
      content: `
      <h3>一、项目初始化</h3>
      <p>使用 npm create vue@latest 初始化项目，选择 TypeScript、Pinia、Vue Router 等必要依赖。</p>
      <h3>二、类型定义规范</h3>
      <p>1. 为接口响应数据定义明确的 TypeScript 接口<br>
      2. 组件 props 使用 interface 定义类型<br>
      3. 避免使用 any 类型，优先使用 unknown + 类型断言</p>
      <h3>三、组件开发技巧</h3>
      <p>1. 使用 script setup 语法糖简化代码<br>
      2. 拆分通用组件（如 Sidebar、Button）<br>
      3. 合理使用 Teleport、Suspense 等高级特性</p>
    `,
      user: {
        uid: 1001,
        loginId: 'frontend_dev',
        nickname: '前端开发工程师',
        avatar: 'https://picsum.photos/seed/author1/40/40',
        intro: '高级开发',
      },
      cateName: '技术讨论',
      media: [
        'https://picsum.photos/seed/vue3/800/400',
        'https://picsum.photos/seed/ts/800/400',
      ],
      createTime: new Date(Date.now() - 3600 * 1000 * 8).toISOString(), // 8小时前
      updateTime: new Date(Date.now() - 3600 * 1000 * 8).toISOString(), // 补充更新时间，与创建时间一致
      likeCount: 128,
      commentCount: 32,
      readCount: 2560,
      collectionCount: 0, // 补充收藏数量
      postTop: 0, // 补充置顶状态
      liked: false,
      collected: false,
      canEdit: postId === 1, // 仅ID=1的帖子可编辑
      canDelete: postId === 1,
    }

    // 加载模拟评论
    comments.value = getMockComments()
    hasMoreComments.value = false
  }

  /** 生成模拟评论列表（严格匹配ServiceComment类型） */
  const getMockComments = (count = 5): ServiceComment[] => {
    const mockUsers = [
      {
        uid: 1002,
        loginId: 'user2',
        nickname: '小明',
        avatar: 'https://picsum.photos/seed/user2/40/40',
        intro: '前端初学者',
      },
      {
        uid: 1003,
        loginId: 'user3',
        nickname: '小红',
        avatar: 'https://picsum.photos/seed/user3/40/40',
        intro: '全栈开发',
      },
      {
        uid: 1004,
        loginId: 'user4',
        nickname: '小李',
        avatar: 'https://picsum.photos/seed/user4/40/40',
        intro: '技术负责人',
      },
      {
        uid: 1005,
        loginId: 'user5',
        nickname: '小张',
        avatar: 'https://picsum.photos/seed/user5/40/40',
        intro: 'UI/UX设计师',
      },
      {
        uid: 1006,
        loginId: 'user6',
        nickname: '小王',
        avatar: 'https://picsum.photos/seed/user6/40/40',
        intro: '后端开发',
      },
    ]

    return Array.from({ length: count }, (_, i) => {
      const author = mockUsers[i % mockUsers.length]
      const isHasReply = i % 2 === 0 // 一半评论有回复

      return {
        id: i + 1,
        uid: author.uid,
        postId: postId,
        content: `非常实用的文章！我在${
          author.intro === '前端初学者' ? '学习Vue 3' : '项目开发'
        }中也遇到过类似问题，按照文章方法解决了~`,
        likeCount: Math.floor(Math.random() * 20) + 1,
        createTime: new Date(
          Date.now() - 3600 * 1000 * (24 - i * 2)
        ).toISOString(),
        status: 1, // 1-正常
        userRespDTO: author, // 严格匹配服务端userRespDTO结构
        liked: false,
        replies: isHasReply
          ? [
              {
                id: i * 100 + 1,
                uid: mockUsers[(i + 1) % mockUsers.length].uid,
                postId: postId,
                pid: i + 1, // 父评论ID
                content: `@${author.nickname} 我也是！特别是${
                  i % 3 === 0 ? '类型定义' : '组件拆分'
                }部分，收获很大`,
                likeCount: Math.floor(Math.random() * 10) + 1,
                createTime: new Date(
                  Date.now() - 3600 * 1000 * (24 - i * 2 - 1)
                ).toISOString(),
                status: 1,
                userRespDTO: mockUsers[(i + 1) % mockUsers.length],
                liked: false,
              },
            ]
          : undefined,
      } as ServiceComment
    })
  }

  /** 生成单条模拟评论（提交失败时用） */
  const getMockComment = (content: string): ServiceComment => {
    return {
      id: Date.now(), // 用时间戳做临时ID
      uid: 1001, // 当前用户ID
      postId: postId,
      content,
      likeCount: 0,
      createTime: new Date().toISOString(),
      status: 1,
      userRespDTO: {
        uid: 1001,
        loginId: 'current_user',
        nickname: '我',
        avatar: 'https://picsum.photos/seed/user1/40/40',
        intro: '当前用户',
      },
      liked: false,
    } as ServiceComment
  }

  // 组件挂载初始化
  // ------------------------------
  onMounted(() => {
    loadCurrentUser()
    loadPostDetail()
  })

  /** 加载当前用户信息 */
  const loadCurrentUser = () => {
    try {
      const userInfo = getUserInfo()
      if (userInfo) {
        currentUser.value = userInfo
      }
      console.log('加载的用户信息:', userInfo)
    } catch (error) {
      console.error('加载用户信息失败:', error)
    }
  }
</script>

<style scoped>
  /* 修复Markdown内容样式（穿透scoped） */
  :global(.prose) :where(h3) {
    color: #111827;
    font-weight: 600;
    margin-top: 1.5rem;
    margin-bottom: 1rem;
  }

  :global(.prose) :where(p) {
    color: #374151;
    margin-top: 1rem;
    margin-bottom: 1rem;
  }

  /* 修复移动端内容遮挡：底部导航栏高度4rem（h-16） */
  @media (max-width: 1023px) {
    main {
      padding-bottom: 4rem;
    }
  }

  /* 图片过渡效果：提升体验 */
  img {
    transition: opacity 0.3s ease;
  }

  img:hover {
    opacity: 0.95;
  }

  /* 评论/回复输入框聚焦样式：统一视觉 */
  textarea:focus,
  input:focus {
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
  }

  /* 点赞图标过渡：平滑变色 */
  :global(.fa-heart),
  :global(.fa-heart-o) {
    transition: color 0.2s ease;
  }
</style>
